package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.feign.BehaviorFeign;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ApUserSearchService apUserSearchService;
    @Autowired
    private BehaviorFeign behaviorFeign;

    final static String  INDEX_NAME ="app_info_article";

    @Override
    public void saveArticle(String articleId, Map article) throws IOException {
        IndexRequest request = new IndexRequest(INDEX_NAME);
        request.id(articleId);
        request.source(JSON.toJSONString(article), XContentType.JSON);
        client.index(request,RequestOptions.DEFAULT);
    }

    @Override
    public void deleteArticle(String articleId) throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest(INDEX_NAME,articleId);
        client.delete(deleteRequest,RequestOptions.DEFAULT);
    }

    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        if (dto==null ||dto.getSearchWords()==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);


        //只有在首页查询的时候才会保存
        if(dto.getFromIndex() == 0){
            ApBehaviorEntry apBehaviorEntry = getEntry(dto);
            if(apBehaviorEntry == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            apUserSearchService.insert(apBehaviorEntry.getId(),dto.getSearchWords());
        }


        if (dto.getMinBehotTime()==null)
            dto.setMinBehotTime(new Date());
        SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery(dto.getSearchWords()).field("title").field("constent").defaultOperator(Operator.OR);
        boolQueryBuilder.must(queryStringQueryBuilder);
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime());
        boolQueryBuilder.filter(rangeQueryBuilder);
        searchSourceBuilder.query(boolQueryBuilder);
        searchSourceBuilder.sort("publishTime", SortOrder.DESC);
        searchSourceBuilder.from(0).size(dto.getPageSize());
        searchRequest.source(searchSourceBuilder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits = response.getHits().getHits();
        List list = new ArrayList<Map>();
        for (SearchHit hit : hits) {
            Map map = JSON.parseObject(hit.getSourceAsString(), Map.class);
            list.add(map);
        }
        return ResponseResult.okResult(list);

    }

    private ApBehaviorEntry getEntry(UserSearchDto userSearchDto) {
        ApUser user = AppThreadLocalUtils.getUser();
        return behaviorFeign.findByUserIdOrEntryId(user.getId(),userSearchDto.getEquipmentId());
    }

}